package middleware

import (
	"fmt"
	"gitee.com/igolang/imoney/internal/common/httpResp"
	"gitee.com/igolang/pkg/xutils"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"log/slog"
)

func RecoverWithLog(log *slog.Logger) gin.HandlerFunc {
	return gin.CustomRecovery(func(ctx *gin.Context, err interface{}) {
		if log == nil {
			return
		}
		req, _ := ctx.Get("$_REQUEST")
		log.LogAttrs(
			ctx,
			slog.LevelError,
			"gin recover from panic",
			slog.String("uri", ctx.Request.RequestURI),
			slog.String("method", ctx.Request.Method),
			slog.String("client_ip", xutils.ClientIp(ctx.Request)),
			slog.Any("$_REQUEST", req),
			slog.String("error", fmt.Sprintf("%+v", errors.Errorf("%+v", err))),
		)
		r := httpResp.Response()
		httpResp.ErrorResponse(httpResp.ErrPanic("%v", err), r)
		httpResp.AbortJSON(ctx, r)
		return
	})
}
